package com.atguigu.controller;

import com.atguigu.entity.UserFollow;
import com.atguigu.entity.UserInfo;
import com.atguigu.entity.vo.UserFollowVo;
import com.atguigu.result.Result;
import com.atguigu.service.UserFollowService;
import com.github.pagehelper.PageInfo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;


@RestController
@RequestMapping("/userFollow")
public class UserFollowController {
    @DubboReference
    private UserFollowService userFollowService;

    @RequestMapping("/auth/follow/{houseId}")
    public Result follow(@PathVariable Long houseId, HttpSession session){
        //获取当前登录的用户信息
        UserInfo userInfo = (UserInfo) session.getAttribute("USER");
        //根据用户id和房源id查询该房源的关注信息
        UserFollow userFollow = userFollowService.findUserFollowByUserIdAndHouseId(userInfo.getId(),houseId);
        //判断userFollow是否为null
        if (userFollow != null){
            //表示当前用户之前关注过该房源但是取消了,将数据库中该数据的is_deleted修改为0
            userFollow.setIsDeleted(0);
            userFollowService.update(userFollow);
        }else {
            //表示当前用户从未关注过该房源，在数据库中添加关注信息
            userFollow = new UserFollow();
            userFollow.setUserId(userInfo.getId());
            userFollow.setHouseId(houseId);
            userFollowService.save(userFollow);
        }
        return Result.ok();
    }

    @RequestMapping("/auth/cancelFollow/{houseId}")
    public Result cancekFollow(@PathVariable Long houseId, HttpSession session){
        //获取当前登录的用户信息
        UserInfo userInfo = (UserInfo) session.getAttribute("USER");
        //根据用户id和房源id查询该房源的关注信息
        UserFollow userFollow = userFollowService.findUserFollowByUserIdAndHouseId(userInfo.getId(),houseId);
        userFollow.setIsDeleted(1);
        userFollowService.update(userFollow);
        return Result.ok();
    }

    @ResponseBody
    @RequestMapping("/auth/list/{pageNum}/{pageSize}")
    public Result findListPage(@PathVariable("pageNum") Integer pageNum, @PathVariable("pageSize") Integer pageSize,HttpSession session){
        UserInfo userInfo = (UserInfo) session.getAttribute("USER");
        PageInfo<UserFollowVo> pageInfo = userFollowService.findUserFollowVoPage(pageNum,pageSize,userInfo.getId());
        return Result.ok(pageInfo);
    }

    @RequestMapping("/auth/cancelFollowById/{id}")
    public Result cancelFollowById(@PathVariable Long id){
        userFollowService.cancelFollowById(id);
        return Result.ok();
    }

}
